<template>
  <BlogHeader :articleInfo="articleInfo" />
  <div class="article">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="18">
        <el-skeleton v-if="loading" :loading="loading" :rows="8" animated />
        <el-card>
          <MdPreview
            v-model="mdState.text"
            :editorId="mdState.id"
            :theme="'light'"
          ></MdPreview>
          <div class="article-info">
            <div class="article-info-inner">
              <div>
                <span>文章作者：</span>
                <a class="to_pointer" href="https://gitee.com/jameswong1">{{
                  articleInfo.authorName
                }}</a>
              </div>
              <div>
                <span>类型：</span>
                <el-tag>{{
                  articleInfo.type == 1
                    ? "原创"
                    : articleInfo.type == 2
                    ? "转载"
                    : "翻译"
                }}</el-tag>
              </div>
              <div v-if="articleInfo.type != 1">
                <span>原文链接：</span>
                <a class="to_pointer" :href="articleInfo.origin_url">{{
                  articleInfo.origin_url
                }}</a>
              </div>
              <div v-else>
                <span>本文链接：</span>
                <a class="to_pointer" v-copy="currentUrl">{{ currentUrl }}</a>
              </div>
              <p>声明: 此文章版权归 HQJ 所有，如有转载，请注明来自原作者</p>
            </div>
            <div v-if="preBlog?.id || nextBlog?.id" class="front_next_article">
              <div
                v-if="preBlog?.id"
                @click="goToArticle(preBlog.id)"
                class="front_next_article_item"
                :style="`background-image: url(${preBlog.article_cover})`"
              >
                <p>< 上一篇</p>
                <p>{{ preBlog.article_title }}</p>
                <div class="front_next_article_hover"></div>
              </div>
              <div
                v-if="nextBlog?.id"
                @click="goToArticle(nextBlog.id)"
                class="front_next_article_item"
                :style="`background-image: url(${nextBlog.article_cover})`"
              >
                <p>下一篇 ></p>
                <p>{{ nextBlog.article_title }}</p>
                <div class="front_next_article_hover"></div>
              </div>
              <!-- <div class="front_next_article_hover"></div> -->
            </div>
          </div>
          <Comments
            id="comments-ref"
            :createId="blogId"
            :type="_Type"
            :comments="commentList"
            :commentTotal="commentTotal"
            @refresh-comment="refreshComment"
          ></Comments>
          <div v-if="recommendList.length" class="recommend-title">推荐</div>
          <div v-if="recommendList.length" class="recommend">
            <el-card
              v-for="item in recommendList"
              :key="item.id"
              @click="goToArticle(item.id)"
            >
              <template #header>
                <span :title="item.article_title" class="title">{{
                  item.article_title
                }}</span>
              </template>
              <el-image class="image" fit="cover" :src="item.article_cover">
                <template #error>
                  <svg-icon name="image404" :width="10" :height="5"></svg-icon>
                </template>
              </el-image>
            </el-card>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="0" :sm="6">
        <el-affix :offset="391" style="width: inherit">
          <el-card header="目录">
            <MdCatalog :editorId="mdState.id" :scroll-element="scrollElement" />
          </el-card>
        </el-affix>
      </el-col>
    </el-row>
    <div class="mobile-catelogue-expand">
      <el-icon @click="toggleDrawer"><Expand /></el-icon>
    </div>
    <!-- 移动端目录 -->
    <el-drawer
      title="目录"
      v-model="drawerShow"
      direction="ltr"
      :before-close="toggleDrawer"
      :append-to-body="true"
      size="60%"
      :z-index="9999"
    >
      <MdCatalog
        v-if="!loading"
        :editorId="mdState.id"
        :scroll-element="scrollElement"
      />
    </el-drawer>
  </div>
  <div class="like-star-share">
    <div>
      <svg
        t="1728019143853"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="2836"
        width="32"
        height="32"
        @click="statusChange('like')"
      >
        <path
          d="M948.4 407.2c-29.2-35.5-76.9-35.5-92.6-35.5H730c10.2-55.2 18.9-119.4 0.2-187.1-12.8-46.6-36.3-79.7-72-101.1-18.7-11.2-38.1-16.9-57.8-16.9-51.8 0-90.6 38.4-96.4 95.7-2.2 21.4-4.2 41.7-9.3 59.1-19 63.9-65.4 112.7-108.3 151.8-16 14.4-33.1 40.2-33.3 69.2-0.6 77.6-0.7 155.5-0.7 235.1l-0.1 141.4c-0.2 47.3 25 85.4 67 101.7 22.2 9 45.7 14 70.1 14.7 38.8 0.5 77.8 0.5 114.3 0.5h56.9c37.2 0 74.4 0 111.8 0.4h1.2c43.5 0 77.7-21.7 93.9-59.5l4.8-11.1c11.3-26 22.9-52.9 30.1-82.8 22-90.9 44.9-188.2 63.4-283.8 7.4-37.9 1.6-68.8-17.4-91.8zM216.1 374.5h-11.9c-56.2 0-101.9 45.7-101.9 101.9v348.4c0 56.2 45.7 101.9 101.9 101.9h11.9c56.2 0 101.9-45.7 101.9-101.9V476.4c0.1-56.2-45.7-101.9-101.9-101.9z"
          :fill="blogStatus.like ? '#3f7ef7' : '#333333'"
          p-id="2837"
        ></path>
      </svg>
      <p :color="blogStatus.like ? '#3f7ef7' : '#333333'">
        {{ articleInfo.thumbs_up_times }}
      </p>
    </div>
    <div>
      <el-icon @click="statusChange('star')"
        ><StarFilled :color="blogStatus.star ? '#3f7ef7' : '#333333'"
      /></el-icon>
      <p :color="blogStatus.star ? '#3f7ef7' : '#333333'">
        {{ articleInfo.star_times }}
      </p>
    </div>
    <div>
      <el-icon @click="focusComment"><Comment /></el-icon>
      <p :color="blogStatus.star ? '#3f7ef7' : '#333333'">
        {{ commentTotal }}
      </p>
    </div>
    <div>
      <el-icon @click="blogStatus.share = !blogStatus.share"><Share /></el-icon>
    </div>
  </div>
</template>
<script setup lang="ts">
import Comments from "@/components/Comments/index.vue";
import { ref, watch, reactive, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import BlogHeader from "@/components/BlogHeader/index.vue";
import { MdPreview, MdCatalog } from "md-editor-v3";
import "md-editor-v3/lib/style.css";

import { queryBlogById, read } from "@/api/blog";
import { ArticleInfo, Likes, RelationArticle } from "@/interface/blogs";
import { ElMessage, ElNotification } from "element-plus";
import { user } from "@/store";
import { getCommentByCreateId } from "@/api/comment";
import { likeSomething, unlikeSomething } from "@/api/like";
import { starSomething, unstarSomething } from "@/api/star";
import { getRelationArticle } from "@/api/blog";
const { getUserInfo, setShowLogin } = user();
const blogStatus = reactive({
  like: false,
  star: false,
  comment: false,
  share: false,
  likeCount: 0,
  starCount: 0,
  commentCount: 0,
});
const _Type = 1;
const router = useRouter();
const route = useRoute();

const currentUrl = window.location.href;

const mdState = reactive({
  text: "",
  id: "my-editor",
  switch: true,
});
const loading = ref<boolean>(false);
const articleInfo = ref<ArticleInfo>({
  createDate: "",
  updateDate: "",
  id: 0,
  article_title: "",
  category_id: 0,
  article_description: "",
  article_content: "",
  article_cover: "",
  is_top: false,
  order: 1,
  status: 1,
  type: 1,
  origin_url: "",
  view_times: 0,
  thumbs_up_times: 0,
  comment_times: 0,
  star_times: 0,
  reading_duration: 0,
  tagIdList: [],
  tagNameList: [],
  authorName: "",
  categoryName: "",
  userId: 0,
  likes: [],
});
const blogId = ref<number>(0);
const scrollElement = document.documentElement;
// 移动端目录是否可见
const drawerShow = ref(false);
// 推荐文章
const recommendList = ref<RelationArticle[]>([]);
const preBlog = ref<RelationArticle>({
  id: 0,
  article_title: "",
  article_cover: "",
});
const nextBlog = ref<RelationArticle>({
  id: 0,
  article_title: "",
  article_cover: "",
});

// 评论内容
const commentList = ref([]);
// 评论总数
const commentTotal = ref<number>(0);
const toggleDrawer = () => {
  drawerShow.value = !drawerShow.value;
};

const goToArticle = (id: number) => {
  router.push({ path: "/blogDetail", query: { id: id } });
};

// // 文章详情
const getArticleDetails = async (id: number) => {
  try {
    const userId = getUserInfo?.id || null;
    const params: { id: number; userId?: number } = { id: id };
    userId ? (params.userId = userId) : "";
    const res = await queryBlogById(params);
    mdState.text = res?.data?.article_content || "";
    const tagNameList = res?.data?.tagNameList.split(",") || [];
    articleInfo.value = Object.assign(res.data, {
      tagNameList: tagNameList,
    });

    // 判断当前用户有没有点赞或收藏
    if (res?.data?.stars.some((star: any) => star.userId === userId)) {
      blogStatus.star = true;
    } else {
      blogStatus.star = false;
    }
    // 游客id为null不考虑游客是否已经点赞
    if (userId && res?.data?.likes.some((like: any) => like.userId === userId)) {
      blogStatus.like = true;
    } else {
      blogStatus.like = false;
    }
    blogId.value = res?.data?.id;
    commentTotal.value = res?.data?.comment_times;
    commentList.value = res?.data?.comments || [];
  } catch (error: any) {
    ElNotification.error({
      title: "Failed",
      message: error?.message || "网络错误",
      offset: 100,
    });
  }
};

const getRelationBlog = (id: number) => {
  getRelationArticle(id)
    .then((res: any) => {
      if (res.status === 200) {
        recommendList.value = res?.data?.recommendList || [];
        nextBlog.value = res?.data?.nextBlog?.[0] || {};
        preBlog.value = res?.data?.preBlog?.[0] || {};
      }
    })
    .catch((error: Error) => console.log(error));
};

const init = async (id: number) => {
  loading.value = true;
  await getArticleDetails(id);
  getRelationBlog(id);
  loading.value = false;
};

// 刷新评论
const refreshComment = async (data: {
  createId: number;
  orderType: string;
}) => {
  const { createId, orderType } = data;
  try {
    // 需要增加userId，因为接口不需token
    const res = await getCommentByCreateId({
      createId: createId,
      userId: getUserInfo.id,
      type: _Type,
      orderType: orderType,
    });
    commentList.value = res?.data?.data;
    commentTotal.value = res?.data?.total || 0;
  } catch (error: any) {
    ElMessage(error?.message || "网络错误");
  }
};

// 点赞收藏交互
const statusChange = async (key: "like" | "star" | "comment" | "share") => {
  switch (key) {
    // 点赞
    case "like":
      try {
        if (!blogStatus.like) {
          // if (!getUserInfo?.id) {
          //   setShowLogin(true);
          //   break;
          // }
          const res = await likeSomething({
            createId: articleInfo.value.id,
            authorId: articleInfo.value.userId,
            userId: getUserInfo.id,
            type: _Type,
          });
          if (res?.status === 201) {
            blogStatus.like = !blogStatus.like;
            articleInfo.value.thumbs_up_times++;
          } else {
            ElNotification.error({
              title: "Failed",
              message: "点赞失败",
              offset: 100,
              duration: 1000,
            });
          }
        } else {
          const userId = getUserInfo?.id || null;
          const likeItem = articleInfo.value.likes.find(
            (like: Likes) => like.type === _Type && like.userId === userId
          );
          const unlikeRes = await unlikeSomething({
            createId: articleInfo.value.id,
            id: likeItem?.id || 0,
            type: _Type, // 1文章 2说说 3评论 4图片
          });
          if (unlikeRes?.status === 201) {
            blogStatus.like = !blogStatus.like;
            articleInfo.value.thumbs_up_times--;
          } else {
            ElNotification.error({
              title: "Failed",
              message: "取消点赞失败",
              offset: 100,
              duration: 1000,
            });
          }
        }
      } catch (error) {
        console.log(error, "error");
      }
      break;
    // 收藏
    case "star":
      if (!getUserInfo?.id) {
        setShowLogin(true);
        break;
      }
      try {
        if (!blogStatus.star) {
          const res = await starSomething({
            createId: articleInfo.value.id,
            authorId: articleInfo.value.userId,
            type: _Type,
          });
          if (res?.status === 201) {
            blogStatus.star = !blogStatus.star;
            articleInfo.value.star_times++;
          } else {
            ElNotification.error({
              title: "Failed",
              message: "收藏失败",
              offset: 100,
              duration: 1000,
            });
          }
        } else {
          const userId = getUserInfo.id;
          const starItem = articleInfo.value.likes.find(
            (star: Likes) => star.type === _Type && star.userId === userId
          );
          const unStarRes = await unstarSomething({
            createId: articleInfo.value.id,
            id: starItem?.id || 0,
            type: _Type, // 1文章 2说说 3评论 4图片
          });
          if (unStarRes?.status === 201) {
            blogStatus.star = !blogStatus.star;
            articleInfo.value.star_times--;
          } else {
            ElNotification.error({
              title: "Failed",
              message: "取消收藏失败",
              offset: 100,
              duration: 1000,
            });
          }
        }
      } catch (error) {
        console.log(error, "error");
      }
      break;
    case "comment":
      break;
    case "share":
      break;
    default:
      break;
  }
};
watch(
  () => route,
  (newValue: any) => {
    if (newValue.path == "/blogDetail" && newValue.query.id) {
      init(newValue.query.id);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const focusComment = () => {
  blogStatus.comment = !blogStatus.comment;
  const dom = document.getElementById("comments-ref");
  dom?.scrollIntoView({
    behavior: "smooth", // 设置滚动行为为平滑滚动，这样过渡更自然，如果不需要平滑滚动可以去掉这个配置项
  });
};
onBeforeUnmount(async () => {
  await read(articleInfo.value.id);
});
</script>

<style lang="scss" scoped>
.article-info {
  padding: 0;
  .article-info-inner {
    padding: 1rem 0;
    font-size: 0.8rem;
  }
  .front_next_article {
    position: relative;
    @include flex($space-between);
    height: 8rem;
    margin-bottom: 2rem;
    color: #ffffff;
    filter: brightness(100%);
    .front_next_article_item {
      position: relative;
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      height: 100%;
      font-weight: bold;
      flex: 1;
      @include flex($center, $center, $column);
      cursor: pointer;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      z-index: 2;
      p {
        filter: brightness(120%);
        z-index: 2;
      }
      .front_next_article_hover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(44, 41, 41, 0.5);
        z-index: 1;
      }
    }
    .front_next_article_item:hover {
      filter: brightness(110%);
    }
  }
}

.mobile-catalog {
  padding: 2rem;
  max-height: 400px;
  scrollbar-width: none;
  overflow-y: auto;
  cursor: pointer;
}

.mobile-catelogue-expand {
  position: fixed;
  top: 60%;
}

.recommend-title {
  margin: 1rem 0 0.5rem 0;
  left: 2.2rem;
  font-size: 1.2rem;
  font-weight: 600;
  color: red;
}

.recommend {
  .el-card {
    height: 12rem;
    overflow: hidden;
    cursor: pointer;
    :deep(.el-card__body) {
      padding: 0;
    }
  }
  .title {
    display: inline-block;
    width: 80%;
    height: 2rem;
    padding: 0.3rem 0 0 0.3rem;
    font-size: 1rem;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
  .image {
    width: 100%;
    height: 10rem;
  }
}

:deep(.el-card__header) {
  font-size: 1rem;
  padding: 0 !important;
  font-weight: bold;
  line-height: 1.8;
  color: var(--font-color);
}

a {
  text-decoration: underline;
}
@media screen and (min-width: 768px) {
  .recommend-title {
    display: block;
  }
  .mobile-catelogue-expand {
    display: none;
  }
  .front_next_article_item {
    font-size: 1.3rem;
  }
  .recommend {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  .article {
    max-width: 1080px;
    margin: 30px auto;
  }
  .like-star-share {
    position: fixed;
    top: 40%;
    right: 4rem;
    @include flex($center, $center, $column);
    font-size: 2rem;
    div {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background-color: #f2f3f5;
      @include flex();
      position: relative;
      cursor: pointer;
      p {
        position: absolute;
        left: 50px;
        top: 0px;
        font-size: 1.2rem;
        border-radius: 30%;
        background-color: #c3c8d0;
        padding: 5px;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  :deep(.md-editor-preview-wrapper) {
    padding: 0;
  }
  .front_next_article_item {
    font-size: 1rem;
  }
  .recommend-title {
    display: block;
  }
  .recommend {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    gap: 8px;
  }
  .like-star-share {
    height: 60px;
    position: fixed;
    bottom: 0;
    @include flex($space-around, $center);
    font-size: 2rem;
    width: 100%;
    background-color: #ffffff;
    border-top: 1px solid #f2f3f5;
    div {
      @include flex();
      position: relative;
      cursor: pointer;
      p {
        position: absolute;
        left: 2rem;
        top: 0px;
        font-size: 0.8rem;
      }
    }
  }
}
</style>
